package com.sm.tool.exception.impl;


import com.sm.tool.entity.response.ReturnData;
import com.sm.tool.enums.ResultEnums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class BadRequestExceptionHandler {


    /**
     *  校验错误拦截处理
     *
     * @param exception 错误信息集合
     * @return 错误信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ReturnData validationBodyException(MethodArgumentNotValidException exception){

        BindingResult result = exception.getBindingResult();
        if (result.hasErrors()) {

            List<ObjectError> errors = result.getAllErrors();

            for (ObjectError objectError:errors) {
                FieldError fieldError = (FieldError) objectError;
                log.error("Data check failure : object{"+fieldError.getObjectName()+"},field{"+fieldError.getField()+
                        "},errorMessage{"+fieldError.getDefaultMessage()+"}");
                return ReturnData.builder().msg(ResultEnums.PARAM_ERROR.getMessage()).code(ResultEnums.PARAM_ERROR.getCode()).build();
            }

        }
        return null;
        //return ReturnData.builder().msg(fieldError.getDefaultMessage()).build();
    }

}
